//
//  YFTrackRecordController.m
//  Victor
//
//  Created by Coollang on 2017/8/16.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "YFTrackRecordController.h"
#import <AVFoundation/AVFoundation.h>
#import "TrackVideo.h"
#import <Photos/Photos.h>
#import "HighlightPropertyView.h"
#import "NSDate+FormateString.h"
#import "IDFileManager.h"
#import "YFRecordVideoRackController.h"
#import "UIDevice+XJDevice.h"
#import "YFThreeDItem.h"
#import <DateTools/DateTools.h>
#import "MyNavigationViewController.h"
#import "YFAlertHelper.h"

typedef void(^PropertyChangeBlock)(AVCaptureDevice *captureDevice);

@interface YFTrackRecordController ()<AVCaptureFileOutputRecordingDelegate>

@property (weak, nonatomic) IBOutlet UIView *leftSuperView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftSuperViewLeftConstraint;
@property (weak, nonatomic) IBOutlet UILabel *recordTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *takeButton;// 拍照按钮
@property (weak, nonatomic) IBOutlet UIButton *reconnectButton;
@property (weak, nonatomic) IBOutlet UILabel *unAuthorizationTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (assign,nonatomic) BOOL enableRotation;//是否允许旋转（注意在视频录制过程中禁止屏幕旋转）

@property (strong,nonatomic) AVCaptureSession *captureSession;//负责输入和输出设置之间的数据传递
@property (strong,nonatomic) AVCaptureDeviceInput *captureDeviceInput;//负责从AVCaptureDevice获得输入数据
@property (strong,nonatomic) AVCaptureMovieFileOutput *captureMovieFileOutput;//视频输出流
@property (strong,nonatomic) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;//相机拍摄预览图层

@property (assign,nonatomic) UIBackgroundTaskIdentifier backgroundTaskIdentifier;//后台任务标识
@property (assign,nonatomic) CGRect *lastBounds;//旋转的前大小
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSDate *startDate;
@property (nonatomic, strong) TrackVideo *video;
@property (nonatomic, strong) HighlightPropertyView *leftArcView;

@property (weak, nonatomic) IBOutlet UIButton *previewVideoView;
@property (nonatomic, strong) CALayer *focusLayer;
@property (nonatomic, strong) NSMutableArray *trackVideos;

@end

@implementation YFTrackRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self preferredInterfaceOrientationForPresentation];
    [self configuerPreviewView];
    [self configuerLeftView];
    [self configureAVCapture];
    [self registerNotification];
    [self unConnectDeviceTip];
    
    _leftSuperViewLeftConstraint.constant = kDevice_Is_iPhoneX?30:0;
    if (kDevice_Is_iPhoneX) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(-30, 0, 30, kYFScreenWidth)];
        view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.7];
        [_leftSuperView addSubview:view];
    }
}

- (void)configerLocalizable {
    self.tipLabel.text = @"Sensor Not Connect";
    [self.reconnectButton setTitle:NSLocalizedString(@"Reconnecting…", nil) forState:UIControlStateNormal];
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![self getAuthorizationState]){
        return;
    }
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES];
    [self.captureSession startRunning];
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    [UIDevice setOrientation:UIInterfaceOrientationPortrait];
    [self.captureSession stopRunning];
}

- (void)dealloc
{
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self];
}

- (void)configuerPreviewView {
    // 设置预览图
    if (self.trackVideos.count > 0 ){
        TrackVideo *lastVideo = self.trackVideos.lastObject;
        [self.previewVideoView setImage:lastVideo.videoImage forState:UIControlStateNormal];
    }else {
        [self.previewVideoView setImage:[UIImage new] forState:UIControlStateNormal];
    }
    self.previewVideoView.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.previewVideoView.clipsToBounds = YES;
}

- (void)configuerLeftView {
    _leftArcView = [[HighlightPropertyView alloc] initWithFrame:CGRectMake(0, 0, 120, kYFScreenWidth)];
    [self.leftSuperView addSubview:_leftArcView];
}
- (void)unConnectDeviceTip{
     __weak typeof(self) weakSelf = self;
    if (![YFCommunicationManager shareInstance].isPeripheralConnected) {
        [UIView animateWithDuration:1.5 animations:^{
            weakSelf.tipLabel.alpha = !weakSelf.tipLabel.alpha;
        } completion:^(BOOL finished) {
            [weakSelf unConnectDeviceTip];
        }];
    }else {
        self.tipLabel.hidden = YES;
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Click shoot to start video record", @"点击 拍摄 即可开始视频录制") inView:self.view afterDelay:2];
    }
}

#pragma mark - deviceAction
- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceDisconnect:) name:kLGPeripheralDidDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceConnected:) name:kLGPeripheralDidConnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackRecordVideoDelete) name:kTrackRecorddelete object:nil];
}

- (void)trackRecordVideoDelete {
    [self.trackVideos removeAllObjects];
    self.trackVideos = nil;
    [self trackVideos];
    [self configuerPreviewView];
}

- (void)enterRealTimeMode {
    __weak __typeof(self) weakSelf = self;
    if ([YFCommunicationManager shareInstance].isPeripheralConnected) {
        [[YFCommunicationManager shareInstance] enterRealTimeModel:^(BOOL success, NSError *error) {
            if (success) {
                [MBProgressHUD showTextHUDWithMessage:   NSLocalizedString(@"Has entered the shooting mode", @"已进入拍摄模式") inView:self.view afterDelay:1.5];
            }
        } realTimeDataCallBlock:^(BOOL success, SportPoseType actionType, NSInteger speed, float strength, NSInteger swingTime, NSInteger hitBallTime, BOOL hitball, NSInteger areaValue, HandDirectionType handType, ServeDirectionType serveDirectionType, JCHandBallType handBallType, NSTimeInterval timeStamp) {
            
            if (success) {
                //展示数据
                NSInteger swingSpeed = [YFUserDefaults generalMetricSystemUnit] ? speed:round([Common kmhToMph:speed]);
                [weakSelf.leftArcView animateToValues:@[@(swingSpeed), @(strength), @(swingTime)]];
                NSInteger swingSecond = (NSInteger)[[NSDate date] secondsLaterThan:weakSelf.startDate];
                
                VideoTrackItem *swingItem = [[VideoTrackItem alloc] initWithSpeed:speed
                                                                         strength:strength
                                                                        swingTime:swingTime
                                                                      swingSecond:swingSecond];
                [weakSelf.video.videoTrackItems addObject:swingItem];
            }else {
                [weakSelf enterRealTimeMode];
            }
        }];
    }
}

- (void)enterWaitingMode
{
    [[YFCommunicationManager shareInstance] quitRealTimeModelCompleted:nil];
}
- (void)handleDeviceDisconnect:(NSNotification *)notification
{
    [self connectingButtonShow:YES];
}

- (void)handleDeviceConnected:(NSNotification *)notification
{
    [self connectingButtonShow:NO];
    [self performSelector:@selector(enter3DMode) withObject:nil afterDelay:0.5f];
}

- (void)connectingButtonShow:(BOOL)isShowing
{
    __weak __typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.5f animations:^{
        weakSelf.reconnectButton.alpha = isShowing ? 1.0f : 0;
    }];
}

#pragma mark - action
- (IBAction)startBtnClick:(UIButton *)sender {
    //根据设备输出获得连接
    AVCaptureConnection *captureConnection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    //根据连接取得设备输出的数据
    if (![self.captureMovieFileOutput isRecording]) {
        self.startDate = [NSDate date];
        [self enterRealTimeMode];
        [self scheduledTimer:YES];
        self.takeButton.selected = YES;
        self.enableRotation = NO;
        //如果支持多任务则则开始多任务
        if ([[UIDevice currentDevice] isMultitaskingSupported]) {
            self.backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
        }
        //预览图层和视频方向保持一致
        captureConnection.videoOrientation = [self.captureVideoPreviewLayer connection].videoOrientation;
        NSString *outputFielPath=[NSTemporaryDirectory() stringByAppendingString:@"myMovie.mov"];
        NSLog(@"save path is :%@",outputFielPath);
        NSURL *fileUrl=[NSURL fileURLWithPath:outputFielPath];
        NSLog(@"fileUrl:%@",fileUrl);
        
        [self.captureMovieFileOutput startRecordingToOutputFileURL:fileUrl recordingDelegate:self];
    }else{
        [self enterWaitingMode];
        [self scheduledTimer:NO];
        self.takeButton.selected = NO;
        [self.captureMovieFileOutput stopRecording];//停止录制
    }
}
    
- (IBAction)closeBtnClick:(id)sender {
    if ([self.captureMovieFileOutput isRecording]) {
        [self startBtnClick:self.takeButton];
    } else {
        _captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        [_captureSession removeInput:_captureDeviceInput];
        [_captureSession removeOutput:_captureMovieFileOutput];
        _captureSession = nil;
        _captureDeviceInput = nil;
        _captureMovieFileOutput = nil;
//        [_captureVideoPreviewLayer removeFromSuperlayer];
//        _captureVideoPreviewLayer = nil;
//        [_leftArcView removeFromSuperview];
//        _leftArcView = nil;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }
}

- (IBAction)preViewButtonClick:(id)sender {
    
    if (self.trackVideos.count > 0 && ![self.captureMovieFileOutput isRecording]) {
        YFRecordVideoRackController *rackVc = [[YFRecordVideoRackController alloc] initWithNibName:@"YFRecordVideoRackController" bundle:nil];
        MyNavigationViewController *nav = [[MyNavigationViewController alloc] initWithRootViewController:rackVc];
//        rackVc.trackVideos = self.trackVideos;
        [self presentViewController:nav animated:YES completion:nil];
    }
}

- (void)updateRecordTime {
    NSInteger swingSecond = (NSInteger)[[NSDate date] secondsLaterThan:self.startDate];
    NSInteger hour = swingSecond / 3600.0;
    NSInteger miutin = (swingSecond % 3600) / 60.0;
    NSInteger second = (swingSecond % 3600) % 60;
    self.recordTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd:%02zd",hour,miutin,second];
}
- (void)scheduledTimer:(BOOL)timerFire {
    if (timerFire) {
        [[self timer] fire];
        self.recordTimeLabel.text = @"00:00:00";
    }else {
        [self.timer invalidate];
        self.recordTimeLabel.text = @"00:00:00";
        self.timer = nil;
    }
}
#pragma mark - 视频输出代理
-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections{
    NSLog(@"开始录制...");
}
-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
    NSLog(@"视频录制完成.");
    __weak typeof(self) weakSelf = self;
    [YFAlertHelper showTwoAlertController:self Title:NSLocalizedString(@"Do you want to save this Live Video？", nil) message:NSLocalizedString(@"If the device disconnect during recording, the missed real-time data will display normally after saved.", nil) cancelTitle:NSLocalizedString(@"Delete", nil) defalutTitle:NSLocalizedString(@"Save", nil) defaultBtnStyle:UIAlertActionStyleDefault cancelAction:^(UIAlertAction *action) {
        
    } defalutAction:^(UIAlertAction *action) {
        //视频录入完成之后在后台将视频存储到相簿
        IDFileManager *manager = [[IDFileManager alloc] init];
        NSString *videoPath = [manager documentPathFromCopyFile:outputFileURL];
        NSLog(@"保存视频路径:%@", videoPath);
        weakSelf.video.path = videoPath;
        weakSelf.video.name = NSLocalizedString(@"Live Video", nil);
        weakSelf.video.creatDate = [NSDate date];
        UIImage *thumbnailImage = [weakSelf.video videoImage];
        NSData *imageData = UIImageJPEGRepresentation(thumbnailImage, 0.5);
        NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        weakSelf.video.imagePath = [NSString stringWithFormat:@"videoImage-%@.png",[NSUUID UUID].UUIDString];
        NSString *imagePath = [documentPath stringByAppendingPathComponent:weakSelf.video.imagePath];
        NSError *error = nil;
        BOOL writeSucc = [imageData writeToFile:imagePath options:0 error:&error];
        NSLog(@"图片写入:%zd error%@",writeSucc,error);
        self.enableRotation = NO;
        [weakSelf.previewVideoView setImage:thumbnailImage forState:UIControlStateNormal];
        weakSelf.takeButton.selected = NO;
        [weakSelf scheduledTimer:NO];
        User *user = [User getLastUser];
        [[RLMRealm defaultRealm] beginWriteTransaction];
        weakSelf.video.name = [NSString stringWithFormat:@"Video %zd", [user.trackVideos count] + 1];
        weakSelf.video.imagePath = weakSelf.video.imagePath;
        [user.trackVideos addObject:weakSelf.video];
        [[RLMRealm defaultRealm] commitWriteTransaction];
        [weakSelf updateTrackVideosAddVideo:weakSelf.video];
        // [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

// video:若为空 怎从本地重新获取
- (void)updateTrackVideosAddVideo:(TrackVideo *)video {
    if (video != nil){
        // 添加一个新的
        [self.trackVideos addObject:video];
        self.video = nil;
    }else {
        [self.trackVideos removeAllObjects];
        self.trackVideos = nil;
        [self trackVideos];
        [self configuerPreviewView];
    }
}

#pragma mark - 相机的相关配置
- (BOOL)getAuthorizationState {
    
    BOOL state = YES;
    //相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
        authStatus == AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
    {
        // 无权限 引导去开启
        //        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        //        if ([[UIApplication sharedApplication]canOpenURL:url]) {
        //            [[UIApplication sharedApplication]openURL:url];
        //        }
        _unAuthorizationTipLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Please allow %@ to access your camera in \"Settings -> Privacy -> Camera\"", nil),[NSString appCurrentName]];
        state = NO;
    }
    
    //麦克风权限
    AVAuthorizationStatus authorMicro = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authorMicro == AVAuthorizationStatusRestricted ||
        authorMicro == AVAuthorizationStatusDenied){
        //无权限 引导去开启
        //        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        //        if ([[UIApplication sharedApplication]canOpenURL:url]) {
        //            [[UIApplication sharedApplication]openURL:url];
        //        }
        _unAuthorizationTipLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Please allow %@ to access your camera in \"Settings -> Privacy -> Micro\"", nil),[NSString appCurrentName]];
        
        state = NO;
    }
    
    //相册权限
    PHAuthorizationStatus photoAuthStatus = [PHPhotoLibrary authorizationStatus];
    if (photoAuthStatus == PHAuthorizationStatusRestricted ||
        photoAuthStatus == PHAuthorizationStatusDenied){
        //无权限 引导去开启
        //        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        //        if ([[UIApplication sharedApplication] canOpenURL:url]) {
        //            [[UIApplication sharedApplication] openURL:url];
        //        }
        _unAuthorizationTipLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Allow %@ to access your album in \"Settings -> Privacy -> Photos\"", nil),[NSString appCurrentName]];
        state = NO;
    }
    _unAuthorizationTipLabel.hidden = state;
    return state;
}
//初始化会话
- (void)configureAVCapture{
    _captureSession = [[AVCaptureSession alloc]init];
    if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) {//设置分辨率
        _captureSession.sessionPreset = AVCaptureSessionPreset1280x720;
    }
    //获得输入设备,取得后置摄像头
    AVCaptureDevice *captureDevice=[self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];
    if (!captureDevice) {
        return;
    }
    //添加一个音频输入设备
    AVCaptureDevice *audioCaptureDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
    
    NSError *error=nil;
    //根据输入设备初始化设备输入对象，用于获得输入数据
    _captureDeviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:captureDevice error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错，错误原因：%@",error.localizedDescription);
        return;
    }
    AVCaptureDeviceInput *audioCaptureDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:audioCaptureDevice error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错，错误原因：%@",error.localizedDescription);
        return;
    }
    //初始化设备输出对象，用于获得输出数据
    _captureMovieFileOutput=[[AVCaptureMovieFileOutput alloc]init];
    
    //将设备输入添加到会话中
    if ([_captureSession canAddInput:_captureDeviceInput]) {
        [_captureSession addInput:_captureDeviceInput];
        [_captureSession addInput:audioCaptureDeviceInput];
        AVCaptureConnection *captureConnection = [_captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
        
        captureConnection.videoOrientation = [self videoOrientationFromCurrentDeviceOrientation];
        if ([captureConnection isVideoStabilizationSupported ]) {
            captureConnection.preferredVideoStabilizationMode =AVCaptureVideoStabilizationModeAuto;
        }
    }
    
    //将设备输出添加到会话中
    if ([_captureSession canAddOutput:_captureMovieFileOutput]) {
        [_captureSession addOutput:_captureMovieFileOutput];
    }
    
    //创建视频预览层，用于实时展示摄像头状态
    _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.captureSession];
    
    CALayer *layer = self.view.layer;
    layer.masksToBounds = YES;
    
    _captureVideoPreviewLayer.connection.videoOrientation
    = [self videoOrientationFromCurrentDeviceOrientation];
    _captureVideoPreviewLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//填充模式
    //将视频预览层添加到界面中
    [layer insertSublayer:_captureVideoPreviewLayer atIndex:0];
    _enableRotation=NO;
    [self addNotificationToCaptureDevice:captureDevice];
    
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cameraViewTapAction:)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    [self.view addGestureRecognizer:singleFingerOne];
}

/**
 *  取得指定位置的摄像头
 *
 *  @param position 摄像头位置
 *
 *  @return 摄像头设备
 */
-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position] == position) {
            return camera;
        }
    }
    return nil;
}
//录制视频的屏幕旋转
- (AVCaptureVideoOrientation)videoOrientationFromCurrentDeviceOrientation {
    return AVCaptureVideoOrientationLandscapeRight;
}
/**
 *  给输入设备添加通知
 */
-(void)addNotificationToCaptureDevice:(AVCaptureDevice *)captureDevice{
    //注意添加区域改变捕获通知必须首先设置设备允许捕获
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        captureDevice.subjectAreaChangeMonitoringEnabled = YES;
    }];
    NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];
    //捕获区域发生改变
    [notificationCenter addObserver:self selector:@selector(areaChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}

/**
 *  改变设备属性的统一操作方法
 *
 *  @param propertyChange 属性改变操作
 */
-(void)changeDeviceProperty:(PropertyChangeBlock)propertyChange{
    AVCaptureDevice *captureDevice= [self.captureDeviceInput device];
    NSError *error;
    //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁
    if ([captureDevice lockForConfiguration:&error]) {
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
    }else{
        NSLog(@"设置设备属性过程发生错误，错误信息：%@",error.localizedDescription);
    }
}

/**
 *  捕获区域改变
 *
 *  @param notification 通知对象
 */
-(void)areaChange:(NSNotification *)notification{
//    YFLog(@"捕获区域改变...");
}
#pragma mark - 相机聚焦
- (void)setfocusImage {
    if(_focusLayer == nil){
        UIImage *focusImage = [UIImage imageNamed:@"focus.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, focusImage.size.width, focusImage.size.height)];
        imageView.image = focusImage;
        CALayer *layer = imageView.layer;
        layer.hidden = YES;
        [_captureVideoPreviewLayer addSublayer:layer];
        _focusLayer = layer;
    }
}

-(void)cameraViewTapAction:(UITapGestureRecognizer *)tgr
{
    if (tgr.state == UIGestureRecognizerStateRecognized && (_focusLayer == NO || _focusLayer.hidden)) {
        CGPoint location = [tgr locationInView:self.view];
        [self setfocusImage];
        [self layerAnimationWithPoint:location];
        
        AVCaptureDevice *device = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];;
        CGPoint pointOfInterest = CGPointMake(0.5f, 0.5f);
        //        NSLog(@"taplocation x = %f y = %f", location.x, location.y);
        CGSize frameSize = [self.view frame].size;
        
        if ( [[self.captureDeviceInput device] position] == AVCaptureDevicePositionFront) {
            location.x = frameSize.width - location.x;
        }
        
        pointOfInterest = CGPointMake(location.y / frameSize.height, 1.f - (location.x / frameSize.width));
        
        if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            NSError *error;
            if ([device lockForConfiguration:&error]) {
                [device setFocusPointOfInterest:pointOfInterest];
                
                [device setFocusMode:AVCaptureFocusModeAutoFocus];
                
                if([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure])
                {
                    [device setExposurePointOfInterest:pointOfInterest];
                    [device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
                }
                
                [device unlockForConfiguration];
                
                //                NSLog(@"FOCUS OK");
            } else {
                //                NSLog(@"ERROR = %@", error);
            }
        }
    }
}
- (void)layerAnimationWithPoint:(CGPoint)point {
    if (_focusLayer) {
        CALayer *focusLayer = _focusLayer;
        focusLayer.hidden = NO;
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        [focusLayer setPosition:point];
        focusLayer.transform = CATransform3DMakeScale(2.0f,2.0f,1.0f);
        [CATransaction commit];
        
        CABasicAnimation *animation = [ CABasicAnimation animationWithKeyPath: @"transform" ];
        animation.toValue = [ NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0f,1.0f,1.0f)];
        //        animation.delegate = self;
        animation.duration = 0.3f;
        animation.repeatCount = 1;
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;
        [focusLayer addAnimation: animation forKey:@"animation"];
        // 0.5秒钟延时
        [self performSelector:@selector(focusLayerNormal) withObject:self afterDelay:0.5f];
    }
}
- (void)focusLayerNormal {
    self.view.userInteractionEnabled = YES;
    _focusLayer.hidden = YES;
}

#pragma mark - getter & setter
- (NSTimer *)timer {
    if (_timer == nil){
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateRecordTime) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (TrackVideo *)video {
    if (_video == nil) {
        _video = [[TrackVideo alloc] init];
    }
    return _video;
}

//想要的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscapeRight;
}
- (BOOL)shouldAutorotate{
    return self.enableRotation;
}
//由模态推出的视图控制器 优先支持的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}
- (NSMutableArray *)trackVideos {
    if (_trackVideos == nil) {
        RLMResults *results = [[User getLastUser].trackVideos sortedResultsUsingKeyPath:@"creatDate" ascending:YES];
        _trackVideos = [NSMutableArray array];
        for (TrackVideo *video in results) {
            [_trackVideos addObject:video];
        }
    }
    return _trackVideos;
}

@end
